package com.example.jack.community.view.home;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.jack.community.BaseFragment;
import com.example.jack.community.MainActivity;
import com.example.jack.community.R;
import com.example.jack.community.common.utils.CustomizeRecyclerView;
import com.example.jack.community.common.utils.CustomizeScrollView;
import com.example.jack.community.data.HomeHostsportBean;
import com.example.jack.community.data.HomeItemBean1;
import com.example.jack.community.data.HomePopularBean;
import com.example.jack.community.data.HomeRcViewpagerBean;
import com.example.jack.community.model.IHomeFragment;
import com.example.jack.community.persenter.HomeFragmentpersenter;
import com.example.jack.community.view.home.homeAdapter.HomeItemAdapter2;
import com.example.jack.community.view.home.homeAdapter.HomeViewpagerAdapter2;
import com.example.jack.community.view.home.homeAdapter.NiceEvenType;
import com.xys.libzxing.zxing.activity.CaptureActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import static android.app.Activity.RESULT_OK;
import static com.example.jack.community.R.id.textView;

/**
 * A simple {@link Fragment} subclass.
 * 首页
 */
public class HomeFragment1 extends BaseFragment implements IHomeFragment {
    public ViewPager mViewPager;
    private LinearLayout mpoint;
    private HomeViewpagerAdapter2 mViewpagerAdapter;
    private ArrayList<HomeRcViewpagerBean> mImageViews;
    private int count = 0;
    private HomeCunstomizeHandler mHandler;
    private HomeFragmentpersenter mHomeFragmentpersenter;

 //  private PopularRecyclerView mPprecyclerview;
  // private HomePpAdapter mHomePpAdapter;

    private HomeItemAdapter2 mHIAdapter;
    private CustomizeRecyclerView mRecyclerView;
    private LinearLayoutManager mRclayoutManager;
    private CustomizeScrollView home_custonmizeScrollView;
    private SwipeRefreshLayout home_swipe_refresh;
    private ImageView home_scanning;

    public static HomeFragment1 newInstance(String s1) {
        HomeFragment1 fragment = new HomeFragment1();
        Bundle args = new Bundle();
        args.putString("agrs1", s1);
        fragment.setArguments(args);
        return fragment;

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);//加上这句话，menu才会显示出来
        //注册成为订阅者
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //解除注册
        EventBus.getDefault().unregister(this);
    }
    //订阅方法，当接收到事件的时候，会调用该方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(NiceEvenType type){
        Toast.makeText(getContext(), "刷新"+type.getReFresh(), Toast.LENGTH_SHORT).show();
        mHIAdapter.notifyData(type.getReFresh(),type.getHomeItemBean1());
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_blank1, container, false);
        initView(view);//初始化控件
        initData(); //初始化数据
        initAdapter(); //初始化适配器
        initSendMessage(); //发送消息
        initListener(); //监听
        mViewPager.setCurrentItem(100);
        return view;
    }

    private void initData() {
        mHomeFragmentpersenter = new HomeFragmentpersenter(this,getContext());
        mHomeFragmentpersenter.loadRcView();
        mHomeFragmentpersenter.loadPpData();
        mHomeFragmentpersenter.loadItemData();
    }

    private void initListener() {
       mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
           @Override
           public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
           }
           @Override
           public void onPageSelected(int position) {
               //这里是模以图片总数这样实现循环播放
               int newpos = position % mImageViews.size();
               //把之前的指示器关闭启用新的指示器，这里就是切换小圆点
               mpoint.getChildAt(newpos).setEnabled(true);
               mpoint.getChildAt(count).setEnabled(false);
               //记录以前的位置以便下个小圆点位置切换
               count = newpos;
           }
           @Override
           public void onPageScrollStateChanged(int state) {

           }
       });

        //首页扫一扫监听
        home_scanning.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission
                        .CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    //checkSelfPermission是自动检查是否有授权，传入一个上下文，和一个要检查的权限
                    //这里的PackageManager.PERMISSION_GRANTED是许可授权的意思
                    ActivityCompat.requestPermissions(getActivity(),
                            new String[]{Manifest.permission.CAMERA}, 1);
                    //requestpermission是请求权限，如果没有权限就向用户请求
                } else {
                    startActivityForResult(new Intent(getContext(), CaptureActivity.class), 0);
                }
            }
        });

        mHIAdapter.setOnItemClikeListener(new HomeItemAdapter2.OnItemClikeListener() {

            @Override
            public void onItemClike(int position, HomeItemBean1 homeItemBean1) {
                Toast.makeText(getContext(), ""+position, Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getContext(), HomeDynamicDetailsActivity.class);
                intent.putExtra("bean",homeItemBean1);
                intent.putExtra("position",position);
                startActivity(intent);
            }

            @Override
            public void onItemPhotoCilck(View view, ArrayList<String> urls, int position) {
                Toast.makeText(getContext(), position + "张图片", Toast.LENGTH_SHORT).show();
                new HomeItemImagesDialog(view.getContext(), urls, position).show();

            }
        });

        home_custonmizeScrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        break;
                    case MotionEvent.ACTION_MOVE:
                        int scrollY = v.getScrollY();
                        int height = v.getHeight();
                        int scrollViewMeasuredHeight = home_custonmizeScrollView.getChildAt(0).getMeasuredHeight();
                        if (scrollY == 0) {
                            System.out.println("滑动到了顶端 view.getScrollY()=" + scrollY);
                        }
                        if ((scrollY + height) == scrollViewMeasuredHeight) {
                            System.out.println("滑动到了底部 scrollY=" + scrollY);
                            System.out.println("滑动到了底部 height=" + height);
                            System.out.println("滑动到了底部 scrollViewMeasuredHeight=" + scrollViewMeasuredHeight);
                            mHIAdapter.changeMoreStatus(HomeItemAdapter2.LOADING_MORE);
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    ArrayList<HomeItemBean1> bean1s = mHomeFragmentpersenter.addItemData2();
                                    mHIAdapter.addItemData(bean1s);
                                    mHIAdapter.changeMoreStatus(HomeItemAdapter2.PULLUP_LOAD_MORE);
                                }
                            },0);
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
        //刷新监听
        home_swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Toast.makeText(getContext(), "在刷新前", Toast.LENGTH_SHORT).show();
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mHIAdapter.clearItemData();
                        ArrayList<HomeItemBean1> bean1s = mHomeFragmentpersenter.updateloadItemData2();
                        mHIAdapter.updateItemData(bean1s);
                        clearMem();
                        home_swipe_refresh.setRefreshing(false);
                    }
                }, 2500);
            }
        });
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        /*调用完requestpermission之后系统会弹出一个对话框让用户选择是否同意授权，然后会回调这个方法，这里的
          grantresults是授权结果 */
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startActivityForResult(new Intent(getContext(), CaptureActivity.class), 0);
                } else {
                    Toast.makeText(getContext(), "not permission", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String result = bundle.getString("result");
            Intent intent = new Intent(getContext(), HomeScanningActivity.class);
            intent.putExtra("key", result);
            startActivity(intent);
        }
    }


    private void initView(View view) {
        mViewPager = (ViewPager) view.findViewById(R.id.home_viewpager);
        mViewPager.setFocusable(true);
        mViewPager.setFocusableInTouchMode(true);
        mViewPager.requestFocus();
        mpoint = (LinearLayout) view.findViewById(R.id.home_ll_point);
        //mPprecyclerview = (PopularRecyclerView) view.findViewById(R.id.home_rv_recommend);
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
      //  mPprecyclerview.setLayoutManager(manager);
        home_scanning = (ImageView) view.findViewById(R.id.home_image_scanning);
        //动态
        mRecyclerView = (CustomizeRecyclerView) view.findViewById(R.id.home_recyclerview);
        mRclayoutManager = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(mRclayoutManager);

        home_custonmizeScrollView = (CustomizeScrollView) view.findViewById(R.id.home_scroll);
        home_swipe_refresh = (SwipeRefreshLayout) view.findViewById(R.id.home_swipe_refresh);
        //设置刷新时动画的颜色，可以设置4个
        home_swipe_refresh.setProgressBackgroundColorSchemeResource(android.R.color.white);
        home_swipe_refresh.setColorSchemeResources(android.R.color.holo_blue_light,
                android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        home_swipe_refresh.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
    }

    private void initAdapter() {
        mViewPager.setCurrentItem(1);
        mpoint.getChildAt(0).setEnabled(true);//默认选中第一个开始
        count = 0;
        mViewPager.setAdapter(mViewpagerAdapter);

      //  mPprecyclerview.setAdapter(mHomePpAdapter);
      // mPprecyclerview.addItemDecoration(new HomePpItemDecoration(30));
        mRecyclerView.setAdapter(mHIAdapter);
    }

    private void initSendMessage() {
        mHandler = new HomeCunstomizeHandler(HomeFragment1.this);
        mHandler.sendEmptyMessageDelayed(0,7000);
        mViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN: //按到轮播图
                        mHandler.removeCallbacksAndMessages(null);//删除发送消息停止轮播
                        break;
                    case MotionEvent.ACTION_UP://没按到或是手指离开轮播图
                        mHandler.sendEmptyMessageDelayed(0,7000);
                        break;
                }
                return false;
            }
        });
    }

    @Override
    public void loadPopularData(ArrayList<HomePopularBean> mdatas) {
        //mHomePpAdapter = new HomePpAdapter(getContext(),mdatas);
    }

    @Override
    public void loadHostsportData(ArrayList<HomeHostsportBean> mdatas) {

    }

    @Override
    public void loadItemData(ArrayList<HomeItemBean1> mdatas) {
        mHIAdapter = new HomeItemAdapter2(getContext(), mdatas);
    }

    @Override
    public void loadRcViewpager(ArrayList<HomeRcViewpagerBean> mbeans) {
            mImageViews = mbeans;
        mViewpagerAdapter = new HomeViewpagerAdapter2(getContext(),mbeans);
        mViewpagerAdapter.notifyDataSetChanged();
    }

    @Override
    public void loadPoint(View view, LinearLayout.LayoutParams params) {
            mpoint.addView(view,params);
    }


}

